package com.zhu.classfile.constant.base;

import com.zhu.classfile.constant.ConstantInfo;
import com.zhu.classfile.constant.ConstantTag;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

//CONSTANT_Utf8_info是常量池中最基础的一种元素,所有其它的常量类型都是对它的引用
//其实局部变量的名字也是在常量池中以utf8形式存在的
public class ConstantUtf8Info implements ConstantInfo {
    private final ConstantTag tag = ConstantTag.CONSTANT_Utf8;
    private String value;

    @Override
    public void readInfo(ByteBuffer reader) {
        int length = Short.toUnsignedInt(reader.getShort());
        byte[] bytes = new byte[length];
        reader.get(bytes);

        // 使用 JDK 提供的 Modified UTF-8 解码
        try {
            // 将 bytes 作为 Modified UTF-8 解码
            this.value = new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("Failed to decode UTF8", e);
        }
    }

    public String getValue() {
        return value;
    }

    @Override
    public ConstantTag getTag() {
        return tag;
    }
}
